<?php

/**
 * 用户请求权限拦截器
 * @package api\components
 */

namespace api\components\filters;

use Yii;
use yii\filters\auth\QueryParamAuth as YiiQueryParamAuth;
use api\common\helpers\Constant;
use api\modules\internal\models\UserCenter;
use yii\web\UnauthorizedHttpException;
use yii\web\BadRequestHttpException;

class ApiQueryParamAuth extends YiiQueryParamAuth
{
    public function authenticate($user, $request, $response)
    {
        $token = Yii::$app->request->get('token');
        if (empty($token)) {
            throw new BadRequestHttpException('登录参数缺失');
        }

        $identity = UserCenter::instance()->loginByToken($token);
        if (empty($identity)) {
            throw new UnauthorizedHttpException('登录失败，请重新登录');
        }

        $redis = Yii::$app->redis;
        $key = Constant::LOGIN_USER_CACHE . '_' . $token;
        $res = $redis->set($key, json_encode($identity));
        if (empty($res)) {
            throw new \Exception('用户身份缓存失败');
        }
        $redis->expire($key, 3600 * 6);
        return $identity;
    }
}
